<template>
  <div class="post-detail max-w-7xl mx-auto my-20">
    <div v-if="loading" class="text-center py-12 text-gray-400">加载中...</div>
    <div v-else-if="error" class="text-center py-12 text-red-500">{{ error }}</div>
    <div v-else-if="post">
      <h1 class="text-3xl font-bold mb-4 text-center">{{ post.title }}</h1>
      <div class="flex items-center justify-center text-sm text-gray-500 mb-6 py-2 space-x-4">
        <span>作者：{{ post.authorName }}</span>
        <span>发布时间：{{ formatTime(post.publishedAt || post.createdAt) }}</span>
        <span>浏览：{{ post.viewCount }}</span>
        <span>点赞：{{ post.likeCount }}</span>
      </div>
      <PreViewMarkdwon :text="post.content" />
      <div id="comments" class="mt-10">评论区...</div>
      <div id="comments" class="mt-10">评论区...</div>
    </div>
    <div v-else class="text-center py-8 text-gray-400">未找到该文章</div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { getArticleDetail, addArticleView } from '@/api/article'
import type { ArticleVO } from '@/types/article'
import PreViewMarkdwon from '@/components/preViewMarkdwon/index.vue'
import 'md-editor-v3/lib/preview.css'

const route = useRoute()
const post = ref<ArticleVO | null>(null)
const loading = ref(true)
const error = ref('')

function formatTime(time: string) {
  if (!time) return ''
  return new Date(time).toLocaleString()
}

onMounted(async () => {
  const id = Number(route.params.id)
  if (!id) {
    error.value = '无效的文章ID'
    loading.value = false
    return
  }
  try {
    // 增加浏览量
    await addArticleView(id)

    const res = await getArticleDetail(id)
    post.value = res as ArticleVO
    // 兼容后端返回格式
    if ((res as any).data) post.value = (res as any).data

  } catch (e: any) {
    error.value = e?.message || '加载失败'
  } finally {
    loading.value = false
  }
})
</script>
<style scoped>
.post-detail h1 {
  line-height: 1.2;
}

.prose {
  color: var(--text-color, #222);
}

.md-editor-catalog {
  position: fixed;
  top: 50%;
  transform: translateY(-50%);
  width: 224px;
  max-height: calc(100vh - 6rem);
  overflow-y: auto;
}
</style>
